package net.cctms.zhishu.webAppFramework.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.Base64;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 位图工具类
 * Created by yf on 2017/8/30.
 */
public class BitmapUtils {

    private static final String TAG = BitmapUtils.class.getSimpleName();

    /**
     * 保存图片
     */
    public static void saveImage(Bitmap Bmp, String filePath) {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        try {
            File path = new File(filePath);// 给新照的照片文件命名
            fos = new FileOutputStream(path);
            bos = new BufferedOutputStream(fos);
            /* 采用压缩转档方法 */
            Bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
			/* 调用flush()方法，更新BufferStream */
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 从Uri中获取Bitmap并根据指定大小上限进行压缩
     *
     * @param uri               位图数据源uri
     * @param minSideLength     所得Bitmap的最小边长（可设置为-1，表示不控制其大小）
     * @param maxNumOfAllPixels 所得Bitmap的大小上限（总像素数）
     * @return 返回压缩后的Bitmap，如果报了OutOfMemoryError或IOException，则返回null
     */
    @Nullable
    public static Bitmap toCompressedBitmapBySizeLimits(Context context, Uri uri, int minSideLength, int maxNumOfAllPixels) {
        ContentResolver cr = context.getContentResolver();
        try {
            // 压缩bitmap
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(cr.openInputStream(uri), null, options);
            options.inSampleSize = computeSampleSize(options, minSideLength, maxNumOfAllPixels);
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeStream(cr.openInputStream(uri), null, options);
        } catch (OutOfMemoryError e) {
            Log.e(TAG, String.format("OutOfMemoryError occurred while decoding %d size bitmap stream.", maxNumOfAllPixels));
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从文件中获取Bitmap并根据指定大小上限进行压缩
     *
     * @param filePath          位图文件路径
     * @param minSideLength     所得Bitmap的最小边长（可设置为-1，表示不控制其大小）
     * @param maxNumOfAllPixels 所得Bitmap的大小上限（总像素数）
     * @return 返回压缩后的Bitmap，如果报了OutOfMemoryError，则返回null
     */
    public static Bitmap toCompressedBitmapBySizeLimits(String filePath, int minSideLength, int maxNumOfAllPixels) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, options);
            options.inSampleSize = computeSampleSize(options, minSideLength, maxNumOfAllPixels);
            // FIXME
            Log.d(TAG, "toCompressedBitmapBySizeLimits() inSampleSize: " + options.inSampleSize);
            options.inJustDecodeBounds = false;
            return toturn(BitmapFactory.decodeFile(filePath, options), readPictureDegree(filePath));
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            Log.e(TAG, String.format("OutOfMemoryError occurred while decoding %d size bitmap file, filePath: %s",
                    maxNumOfAllPixels,
                    filePath));
            return null;
        }
    }

    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    public static Bitmap toturn(Bitmap img, int degree) {
        if (degree != 0) {
            Matrix matrix = new Matrix();
            matrix.postRotate(degree);
            int width = img.getWidth();
            int height = img.getHeight();
            img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);
        }
        return img;
    }

    /**
     * 得到位图压缩比
     *
     * @param minSideLength  最小边长
     * @param maxNumOfPixels 期望的最大像素数
     * @return 位图大小压缩比
     */
    private static int computeSampleSize(BitmapFactory.Options options,
                                         int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);

        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }

        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options,
                                                int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 :
                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 :
                (int) Math.min(Math.floor(w / minSideLength),
                        Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) &&
                (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    //图片质量压缩
    private static Bitmap compressImage(Bitmap image) {
        if (null == image) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        Log.i(TAG, "compressImage baos.toByteArray().length-1-->" + baos.toByteArray().length / 1024);
        while (baos.toByteArray().length / 1024 > 500) {    //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            Log.i(TAG, "compressImage baos.toByteArray().length--->" + baos.toByteArray().length / 1024);
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
        }
        if (!image.isRecycled()) {
            image.recycle();
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        return BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
    }


    public static Bitmap comp(Bitmap image, float hh, float ww) {
        if (null == image) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        Log.i(TAG, "comp baos.toByteArray().length1--->" + baos.toByteArray().length / 1024);
        if (baos.toByteArray().length / 1024 > 500) {//判断如果图片大于500k,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
        }
        if (!image.isRecycled()) {
            image.recycle();
        }
        Log.i(TAG, "comp baos.toByteArray().length2--->" + baos.toByteArray().length / 1024);
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        Log.i(TAG, "w-->" + w);
        Log.i(TAG, "h-->" + h);

        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w >= h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;//降低图片从ARGB888到RGB565
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        Log.i(TAG, "bitmap-getWidth-->" + bitmap.getWidth());
        Log.i(TAG, "bitmap-getHeight-->" + bitmap.getHeight());
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
    }

    /**
     * 将base64码转成bitmap
     *
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

}
